package com.bfxy.rabbit.consumer.component;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitReceive {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 组合使用监听
     * @RabbitListener @QueueBinding @Queue @Exchange
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${zdp.rabbitmq.test.queue.name}",
                            durable = "${zdp.rabbitmq.test.queue.durable}"),
                    exchange = @Exchange(value = "${zdp.rabbitmq.test.exchange.name}",
                                durable = "${zdp.rabbitmq.test.exchange.durable}",
                                type = "${zdp.rabbitmq.test.exchange.type}",
                                ignoreDeclarationExceptions = "${zdp.rabbitmq.test.exchange.ignoreDeclarationExceptions}"),
                    key = "${zdp.rabbitmq.test.key}"
            )
    )
    // 监听队列，处理消息
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {
        // 1. 收到消息后 进行业务端消费处理
        System.out.println("---------------------");
        System.out.println("---------消费消息 " + message.getPayload());

        // 2.处理成功之后，获取到deliveryTag，并进行手工的ACK操作。
        // 因为我们配置文件中配置的是手工签收方式
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        /**
         * 手工签收
         * deliveryTag : 通过 MessageHeaders传过来的，broker自动生成deliveryTag
         * multiple :  是否支持批量
         */
        channel.basicAck(deliveryTag,false);
    }
}
